package com.shengzhe.ostudent.utils.page;

import com.shengzhe.ostudent.utils.jdbc.DaoUtils;
import lombok.Data;
import lombok.experimental.Accessors;

import java.lang.reflect.Field;
import java.util.List;

@Data
@Accessors(chain = true)
public class PageInfo<T> extends PageEntity {
    private List<T> list;

    // 总结果
    private long total = 0;

    // 剩余页数
    private long page = 1;

    public PageInfo(Class<?> clazz, List<T> personnelList, Object condition) {
        // 判断list是否有值
        if (personnelList != null && !personnelList.isEmpty()) {
            // 通过反射求出当前列表在数据库中的总数据，构建出分页数据
            this.total = DaoUtils.count(clazz, condition);
            Class<?> conditionClass = condition.getClass();
            try {
                Field pageSizeField = conditionClass.getDeclaredField("pageSize");
                Field pageNumField = conditionClass.getDeclaredField("pageNum");
                pageSizeField.setAccessible(true);
                pageNumField.setAccessible(true);
                Object objSize = pageSizeField.get(condition);
                Object objNum = pageNumField.get(condition);
                int pageNum = Integer.parseInt(String.valueOf(objNum));
                int pageSize = Integer.parseInt(String.valueOf(objSize));
                this.page = this.total / pageSize;
                setPageNum(pageNum);
                setPageSize(pageSize);
            } catch (IllegalAccessException | NoSuchFieldException e) {
                e.printStackTrace();
                this.page = 1;
                this.total = 0;
            }


        }

        this.list = personnelList;
    }

    public PageInfo(List<T> personnelList) {
        if (personnelList != null && !personnelList.isEmpty()) {
            Class<?> clazz = personnelList.get(0).getClass();
        }

        this.list = personnelList;
    }

    public PageInfo() {
    }
}
